package com.syy.spider.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.imageclassify.AipImageClassify;
import com.syy.spider.dao.SpiderMapper;
import com.syy.spider.pojo.*;
import com.syy.spider.service.SpiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class SpiderController {
    @Autowired
    private SpiderMapper spiderMapper;
    @Autowired
    private SpiderService spiderService;
    @RequestMapping("/center")
    public String toCenter(){
        return "pages/center";
    }

    @RequestMapping("/notice")
    public String toNotice(){
        return "pages/notice";
    }

    @RequestMapping("/index")
    public String toIndex(){
        return "pages/index";
    }

    @RequestMapping("/toDetails")
    public String toDetails(){
        return "pages/pictureDetails";
    }
    //爬取页面控制
    @RequestMapping("/spider")
    public String spider(HttpServletRequest request, HttpSession session){
        User user = (User) request.getSession().getAttribute("user");
        if (user!=null){
            String username = user.getUsername();
            String spiderName = request.getParameter("spiderName");
            String html = spiderService.getHtml(spiderName);
            List<Picture> pictures = getPictureList(html);
            pictures.forEach(var->{
                var.setUsername(username);
                var.setTitle(spiderName);
                var.setSpiderTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            });
            request.getSession().setAttribute("picturesNotWarehousing",pictures);
        }else {
            String spiderName = request.getParameter("spiderName");
            String html = spiderService.getHtml(spiderName);
            List<Picture> pictures = getPictureList(html);
            pictures.forEach(var->{
                var.setTitle(spiderName);
                var.setSpiderTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            });
            request.getSession().setAttribute("picturesNotWarehousing",pictures);
        }
        return "pages/pictureSpiderOk";
    }

    private List<Picture> getPictureList(String html) {
        List<Picture> pictures = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(html);
        System.out.println(jsonObject);
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < 30; i++) {
            Picture picture = new Picture();
            JSONObject info = data.getJSONObject(i);
            //图片链接
            String thumbURL = info.getString("thumbURL");
            System.out.println("图片链接：" + thumbURL);
            if (thumbURL!=null){
                picture.setJustImgUrl(thumbURL);
            }
            //图片名称
            //https://img0.baidu.com/it/u=1390129292,1866210259&fm=253&fmt=auto&app=138&f=JPEG?w=333&h=500
            String name = thumbURL.replace("https://img0.baidu.com/it/u=","");
            name = name.substring(0,name.indexOf("&"));
            if (name!=null){
                picture.setName(name);
            }
            //图片描述
            String fromPageTitleEnc = info.getString("fromPageTitleEnc");
            System.out.println("图片描述：" + fromPageTitleEnc);
            if (fromPageTitleEnc!=null){
                picture.setDescription(fromPageTitleEnc);
            }
            //图片来源的网站
            String fromURLHost = info.getString("fromURLHost");
            if (!fromURLHost.contains("https://")){
                fromURLHost ="https://" + fromURLHost;
            }
            System.out.println("图片来自的网站：" + fromURLHost);
            if (fromURLHost!=null){
                picture.setHostUrl(fromURLHost);
            }
            //
            JSONArray replaceUrl = info.getJSONArray("replaceUrl");
            if (replaceUrl!=null) {
//                System.out.println(replaceUrl.size());
                String fromUrl = replaceUrl.getJSONObject(0).getString("FromUrl");
                System.out.println("图片可能来源网站：" + fromUrl);
                if (fromUrl!=null){
                    picture.setUrl(fromUrl);
                }
            }
            pictures.add(picture);
        }
        return pictures;
    }

    @PostMapping("/display")
    @ResponseBody
    public List<Picture> display(HttpServletRequest request, HttpSession session,@RequestBody Map<String, Object> params){
        int id = (int) params.get("id");
        String title = spiderService.getTitle(id);
        User user = (User) request.getSession().getAttribute("user");
        String username = user.getUsername();
        System.out.println("开始查询"+title+"图片");
//        System.out.println("欢迎用户"+session.getAttribute("username")+"登录");
        return spiderService.getImgs(username,title);
    }
    @RequestMapping("/displayHtml")
    public String diaplayHtml(){
        return "pages/pictureDisplay";
    }

    @RequestMapping("/spiderHtml")
    public String spiderHtml(){
        return "pages/pictureSpider";
    }

    @RequestMapping("/headHtml")
    public String headHtml(){
        return "pages/header";
    }

    @PostMapping("/getTitle")
    @ResponseBody
    public List<User_title> getTitle(HttpServletRequest request, HttpSession session){
        User user = (User) request.getSession().getAttribute("user");
        String username = user.getUsername();
        return spiderService.getUserTitle(username);
    }
    @PostMapping("/shengxu")
    @ResponseBody
    public List<User_title> getTitleshengxu(HttpServletRequest request, HttpSession session){
        User user = (User) request.getSession().getAttribute("user");
        String username = user.getUsername();
        return spiderMapper.getUserTitleshengxu(username);
    }
    @PostMapping("/jiangxu")
    @ResponseBody
    public List<User_title> getTitlejiangxu(HttpServletRequest request, HttpSession session){
        User user = (User) request.getSession().getAttribute("user");
        String username = user.getUsername();
        return spiderMapper.getUserTitlejiangxu(username);
    }
    @RequestMapping("/self")
    public String toSelf(){
        return "pages/self";
    }
    @RequestMapping("/record")
    public String toRecord(){
        return "pages/record";
    }

    @RequestMapping("/getPicturesNotWarehousing")
    @ResponseBody
    public List<Picture> getPicturesNotWarehousing(HttpServletRequest request, HttpSession session){
        List<Picture> pictures = (List<Picture>) request.getSession().getAttribute("picturesNotWarehousing");
        System.out.println("爬取到的图片为：" + pictures);
        return pictures;
    }

    @RequestMapping("/addPicture")
    @ResponseBody
    public void addPicture(@RequestBody Map<String, Object> params){
        LinkedHashMap<String, String> a = (LinkedHashMap<String, String>) params.get("picture");
        Picture picture = new Picture();
        picture.setName(a.get("name"));
        picture.setDescription(a.get("description"));
        picture.setJustImgUrl(a.get("justImgUrl"));
        picture.setUrl(a.get("url"));
        picture.setTitle(a.get("title"));
        picture.setUsername(a.get("username"));
        picture.setHostUrl(a.get("hostUrl"));
        picture.setSpiderTime(a.get("spiderTime"));
        System.out.println(picture);
        try {
            spiderService.insertPicInfo(picture);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            spiderService.insertTitle(picture.getUsername(),picture.getTitle());
        } catch (Exception e) {
            System.out.println("主题重复忽略");
        }
    }

    @RequestMapping("/getPictureDetail")
    @ResponseBody
    public Picture getPictureDetail(HttpServletRequest request, HttpSession session,@RequestBody Map<String, Object> params){
        int picId = Integer.parseInt((String) params.get("picId"));
        return spiderService.selectPictureById(picId);
    }

    @RequestMapping("/deleteFav")
    @ResponseBody
    public int deleteFav(HttpServletRequest request,@RequestBody Map<String, Object> params){
        User user = (User) request.getSession().getAttribute("user");
        String username = user.getUsername();
        int id = (int) params.get("id");
        Picture picture = spiderService.selectPictureById(id);
        String title = picture.getTitle();
        int a = spiderService.deleteFav(id);
        List<Picture> pictures = spiderService.selectPicturesByTitle(username,title);
        if (pictures.size()==0){
            spiderService.deleteTitle(username,title);
        }
        System.out.println(a);
        return a;
    }

    @RequestMapping("/download")
    @ResponseBody
    public int download(@RequestBody Map<String, Object> params){
        int id = (int) params.get("id");
        Picture picture = spiderService.selectPictureById(id);
        try {
            spiderService.downLoad(picture);
        } catch (IOException e) {
            return 0;
        }
        return 1;
    }

//    @LoggerAnno(funcName="上传新闻缩略图")
    @RequestMapping("/uploadImage")
    @ResponseBody
    public int uploadArticleImage(HttpServletRequest request, MultipartFile file) {
        System.out.println("进入上传后端方法！");
        String oldName = file.getOriginalFilename();
        System.out.println(oldName);


        // 判断文件是否为空
        if (file == null || file.getSize() == 0) {
            System.out.println("文件是空！");
        }else {
            System.out.println("文件不是空");
        }
        return 1;
    }

    @RequestMapping("/tuxiangshibie")
    public String tuxiangshibie(MultipartFile file, HttpServletRequest request){
        String APP_ID = "26017604";
        String API_KEY = "5TrYMjEGmyhPGMYH3nQ7gyB3";
        String SECRET_KEY = "xdYojh1zUTam0GTifnL5wOiZBG7M1GiN";
        System.out.println(file.getOriginalFilename());
        // 初始化一个AipImageClassify
        AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("baike_num", "5");
        options.put("result_num", "10");
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bt = new byte[0];
        try {
            bt = toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        org.json.JSONObject res = client.advancedGeneral(bt, options);
        String s = res.toString(2);
        s = s.replaceAll(" ","");
        RecognitionResultAll recognitionResult = JSONObject.parseObject(s, RecognitionResultAll.class);
        System.out.println(recognitionResult);
        List<RecognitionResult> result = recognitionResult.getResult();
        String keyword = result.get(0).getKeyword();
        List<Picture> pictures = new ArrayList<>();
        result.forEach(var->{
            Picture picture = new Picture();
            picture.setTitle(keyword);
            picture.setDescription(var.getBaike_info().getDescription());
            picture.setJustImgUrl(var.getBaike_info().getImage_url());
            picture.setSpiderTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            pictures.add(picture);
        });
        request.getSession().setAttribute("picturesNotWarehousing",pictures);
        return "pages/pictureSpiderOk";
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
}
